<template>
  <div id="app">
    <div>
      <span>姓名:</span>
      <input type="text" v-model.trim="uname"/>
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model="age"/>
    </div>
    <div>
      <span>性别:</span>
      <select v-model="gender">
        <option value="男" >男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="add">添加/修改</button>
    </div>
    <div>
      <table
        border="1"
        cellpadding="10"
        cellspacing="0"
      >
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="item in lis" :key="item.id">
          <td>{{item.id}}</td>
          <td>{{item.uname}}</td>
          <td>{{item.age}}</td>
          <td>{{item.gender}}</td>
          <td>
            <button @click="remove(item.id)">删除</button>
            <button @click="edit(item.id)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  data(){
    return{
      lis:JSON.parse(localStorage.getItem('lis'))||[],
      gender:[],
      uname:'',
      age:'',
      dealevent:"add",
      editid:''
    }
  },
  watch:{
    lis:{
      deep:true,
      handler(nval){
      localStorage.setItem("lis",JSON.stringify(nval))
    }
    }
  },
  methods:{
    add(){
      if(this.dealevent==='add'){
        if(this.gender.length===0||this.uname==''||this.age=='')return alert("请输入有效数据")
        this.lis.push({
          id:this.lis[this.lis.length-1].id+1,
          gender:this.gender,
          uname:this.uname,
          age:this.age,
        })
        this.age=''
      }else if(this.dealevent==='edit'){
        this.lis.splice(this.lis.findIndex(item=>item.id===this.editid),1,
        {
          id:this.editid,
          gender:this.gender,
          uname:this.uname,
          age:this.age,
        })
        
      }
      this.gender=''
      this.uname=''
      this.age=''
      this.dealevent='add'
    },
    remove(id){
      this.lis.splice(this.lis.findIndex(item=>item.id===id),1)
    },
    edit(id){
      this.dealevent='edit'
      this.editid=id
      const item=this.lis.find(item=>item.id===id)
      this.gender=item.gender
      this.uname=item.uname
      this.age=item.age
    }
  }
}
</script>